package model

import (
	"bytes"
	"errors"
	"github.com/jmoiron/sqlx"
	"strings"
	"time"
)

// 设站信息
type Tpssetups struct {
	ID                    int       `db:"ID"`                    //设站标识ID
	SensorID              int       `db:"Sensor_ID"`             //关联的传感器ID
	PointID               int       `db:"Point_ID"`              //测点ID值
	Name                  string    `db:"Name"`                  //测站名
	Epoch                 time.Time `db:"Epoch"`                 //观测时间
	Description           string    `db:"Description"`           //备注
	InstrumentHeight      float64   `db:"InstrumentHeight"`      //仪器高
	Orientation           float64   `db:"Orientation"`           //后视方位角
	TransverseTilt        float64   `db:"TransverseTilt"`        //后方交会时残差1
	LongitudeTilt         float64   `db:"LongitudeTilt"`         //后方交会时残差2
	HCircleIndexCorr      float64   `db:"HCircleIndexCorr"`      //后方交会时残差3
	VCircleIndexCorr      float64   `db:"VCircleIndexCorr"`      //后方交会时残差4
	ExEasting             float64   `db:"ExEasting"`             //测站东
	ExNorthing            float64   `db:"ExNorthing"`            //测站北
	ExHeight              float64   `db:"ExHeight"`              //测站高
	Type                  int16     `db:"Type"`                  //设站类别
	TpsConstant           float64   `db:"TpsConstant"`           //仪器加常数(m)
	TpsConstantPpm        float64   `db:"TpsConstantPpm"`        //仪器乘常数(ppm)
	Temperature           float64   `db:"Temperature"`           //干温度(℃)
	RelativeTemperature   float64   `db:"RelativeTemperature"`   //相对湿度(%)
	Pressure              float64   `db:"Pressure"`              //气压(mb)
	TpsName               string    `db:"TpsName"`               //仪器型号
	TpsNo                 string    `db:"TpsNo"`                 //仪器硬件编号
	AnalyzerColumnBitMask int       `db:"AnalyzerColumnBitMask"` //预留
	State                 int16     `db:"State"`                 //状态
	CustomTextN           string    `db:"CustomTextN"`           //备注2
}

// 根据【设站标识ID】查询【设站信息】表中是否存在相关记录
func (d *Tpssetups) Exist(ID int) (bool, error) {
	rows, err := amp.Queryx("SELECT COUNT(0) Count FROM tpssetups WHERE ID=?", ID)
	if err != nil {
		return false, err
	}
	defer rows.Close()
	count := 0
	if rows.Next() {
		err = rows.Scan(&count)
		if err != nil {
			return false, err
		}
		return count > 0, nil
	}
	return false, nil
}

// 插入单条记录到【设站信息】表中
func (d *Tpssetups) Insert() (int64, error) {
	result, err := amp.Exec("INSERT INTO tpssetups(Sensor_ID,Point_ID,Name,Epoch,Description,InstrumentHeight,Orientation,TransverseTilt,LongitudeTilt,HCircleIndexCorr,VCircleIndexCorr,ExEasting,ExNorthing,ExHeight,Type,TpsConstant,TpsConstantPpm,Temperature,RelativeTemperature,Pressure,TpsName,TpsNo,AnalyzerColumnBitMask,State,CustomTextN) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", d.SensorID, d.PointID, d.Name, d.Epoch, d.Description, d.InstrumentHeight, d.Orientation, d.TransverseTilt, d.LongitudeTilt, d.HCircleIndexCorr, d.VCircleIndexCorr, d.ExEasting, d.ExNorthing, d.ExHeight, d.Type, d.TpsConstant, d.TpsConstantPpm, d.Temperature, d.RelativeTemperature, d.Pressure, d.TpsName, d.TpsNo, d.AnalyzerColumnBitMask, d.State, d.CustomTextN)
	if err != nil {
		return -1, err
	}
	return result.LastInsertId()
}

// 根据【设站标识ID】修改【设站信息】表的单条记录
func (d *Tpssetups) Update() (bool, error) {
	result, err := amp.Exec("UPDATE tpssetups SET Sensor_ID=?, Point_ID=?, Name=?, Epoch=?, Description=?, InstrumentHeight=?, Orientation=?, TransverseTilt=?, LongitudeTilt=?, HCircleIndexCorr=?, VCircleIndexCorr=?, ExEasting=?, ExNorthing=?, ExHeight=?, Type=?, TpsConstant=?, TpsConstantPpm=?, Temperature=?, RelativeTemperature=?, Pressure=?, TpsName=?, TpsNo=?, AnalyzerColumnBitMask=?, State=?, CustomTextN=? WHERE ID=?", d.SensorID, d.PointID, d.Name, d.Epoch, d.Description, d.InstrumentHeight, d.Orientation, d.TransverseTilt, d.LongitudeTilt, d.HCircleIndexCorr, d.VCircleIndexCorr, d.ExEasting, d.ExNorthing, d.ExHeight, d.Type, d.TpsConstant, d.TpsConstantPpm, d.Temperature, d.RelativeTemperature, d.Pressure, d.TpsName, d.TpsNo, d.AnalyzerColumnBitMask, d.State, d.CustomTextN, d.ID)
	if err != nil {
		return false, err
	}
	affected, err := result.RowsAffected()
	if err != nil {
		return false, err
	}
	return affected > 0, nil
}

// 根据【设站标识ID】查询【设站信息】表中的单条记录
func (d *Tpssetups) Get(ID int) (tpssetups Tpssetups, err error) {
	rows, err := amp.Queryx("SELECT ID, Sensor_ID, Point_ID, Name, Epoch, Description, InstrumentHeight, Orientation, TransverseTilt, LongitudeTilt, HCircleIndexCorr, VCircleIndexCorr, ExEasting, ExNorthing, ExHeight, Type, TpsConstant, TpsConstantPpm, Temperature, RelativeTemperature, Pressure, TpsName, TpsNo, AnalyzerColumnBitMask, State, CustomTextN FROM tpssetups WHERE ID=?", ID)
	if err != nil {
		return tpssetups, err
	}
	defer rows.Close()
	tpssetupss, err := d._RowsToArray(rows)
	if err != nil {
		return tpssetups, err
	}
	if len(tpssetupss) <= 0 {
		return tpssetups, err
	}
	return tpssetupss[0], nil
}

// 根据【设站标识ID】数组查询【设站信息】表中的多条记录
func (d *Tpssetups) GetIn(IDs []int) (tpssetupss []Tpssetups, err error) {
	if len(IDs) <= 0 {
		return tpssetupss, errors.New("IDs is empty")
	}
	sqlStr := bytes.Buffer{}
	sqlStr.WriteString("SELECT ID, Sensor_ID, Point_ID, Name, Epoch, Description, InstrumentHeight, Orientation, TransverseTilt, LongitudeTilt, HCircleIndexCorr, VCircleIndexCorr, ExEasting, ExNorthing, ExHeight, Type, TpsConstant, TpsConstantPpm, Temperature, RelativeTemperature, Pressure, TpsName, TpsNo, AnalyzerColumnBitMask, State, CustomTextN FROM ")
	sqlStr.WriteString("tpssetups")
	sqlStr.WriteString(" WHERE ID IN(")
	paramKeys := strings.Repeat("?,", len(IDs))
	sqlStr.WriteString(paramKeys[:len(paramKeys)-1])
	sqlStr.WriteString(")")
	var rows *sqlx.Rows
	vals := make([]interface{}, 0, len(IDs))
	for _, v := range IDs {
		vals = append(vals, v)
	}
	rows, err = amp.Queryx(sqlStr.String(), vals...)
	if err != nil {
		return tpssetupss, err
	}
	defer rows.Close()
	return d._RowsToArray(rows)
}

// 查询【设站信息】表总记录数
func (d *Tpssetups) GetRowCount() (count int, err error) {
	rows, err := amp.Queryx("SELECT COUNT(0) Count FROM tpssetups")
	if err != nil {
		return -1, err
	}
	defer rows.Close()
	if rows.Next() {
		err = rows.Scan(&count)
		if err != nil {
			return -1, err
		}
		return count, nil
	}
	return -1, nil
}

// 分页查询【设站信息】表的记录
func (d *Tpssetups) GetRowList(PageIndex, PageSize int) (tpssetupss []Tpssetups, err error) {
	rows, err := amp.Queryx("SELECT ID, Sensor_ID, Point_ID, Name, Epoch, Description, InstrumentHeight, Orientation, TransverseTilt, LongitudeTilt, HCircleIndexCorr, VCircleIndexCorr, ExEasting, ExNorthing, ExHeight, Type, TpsConstant, TpsConstantPpm, Temperature, RelativeTemperature, Pressure, TpsName, TpsNo, AnalyzerColumnBitMask, State, CustomTextN FROM tpssetups LIMIT ?,?", (PageIndex-1)*PageSize, PageSize)
	if err != nil {
		return tpssetupss, err
	}
	defer rows.Close()
	return d._RowsToArray(rows)
}

// 解析【设站信息】表记录
func (d *Tpssetups) _RowsToArray(rows *sqlx.Rows) (models []Tpssetups, err error) {
	for rows.Next() {
		mo := Tpssetups{}
		err = rows.Scan(&mo.ID, &mo.SensorID, &mo.PointID, &mo.Name, &mo.Epoch, &mo.Description, &mo.InstrumentHeight, &mo.Orientation, &mo.TransverseTilt, &mo.LongitudeTilt, &mo.HCircleIndexCorr, &mo.VCircleIndexCorr, &mo.ExEasting, &mo.ExNorthing, &mo.ExHeight, &mo.Type, &mo.TpsConstant, &mo.TpsConstantPpm, &mo.Temperature, &mo.RelativeTemperature, &mo.Pressure, &mo.TpsName, &mo.TpsNo, &mo.AnalyzerColumnBitMask, &mo.State, &mo.CustomTextN)
		if err != nil {
			return models, err
		}
		models = append(models, mo)
	}
	return models, err
}
